package javaweb_work01.Filter;

import javaweb_work01.login.Entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断sesstion中是否有用户名信息
        //将ServletRequest对象强转为HttpServletRequest对象
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        //得到Session
        HttpSession session = httpServletRequest.getSession();
        //得到User对象
        User user = (User) session.getAttribute("user");

        //获取路径
        String servletPath = httpServletRequest.getServletPath();

        System.out.println("执行");
        //判断，如没有user对象,且路径中不包含index，则跳转回登录页面
        if((null == user || "" == user.getPassword()) && !servletPath.contains("index")){
            //服务器内跳转
            httpServletRequest.getRequestDispatcher("index.jsp").forward(servletRequest,servletResponse);
            //否则放行
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
